import 'package:get/get.dart';
import 'package:flutter/material.dart';
import '../data/models/emotion_record.dart';
import '../data/repositories/emotion_repository.dart';
import '../data/repositories/emotion_repository_impl.dart';
import '../data/repositories/media_repository.dart' as media_repo;
import '../data/repositories/media_repository_impl.dart' as media_impl;
import '../core/utils/app_utils.dart';

/// 记录详情控制器
/// Record detail controller
class RecordDetailController extends GetxController {
  // 数据仓库
  // Data repositories
  final EmotionRepository _emotionRepository = EmotionRepositoryImpl();
  final media_repo.MediaRepository _mediaRepository = media_impl.MediaRepositoryImpl();
  
  // 响应式状态变量
  // Reactive state variables
  final record = Rx<EmotionRecord?>(null);
  final mediaFiles = <MediaFile>[].obs;
  final isLoading = false.obs;
  final isEditing = false.obs;
  final errorMessage = ''.obs;
  
  // 编辑状态的表单控制器
  // Form controllers for editing state
  final TextEditingController contentController = TextEditingController();
  final selectedIntensity = 5.obs;
  
  // 音频播放相关
  // Audio playback related
  final isPlaying = false.obs;
  final currentPlayingPath = ''.obs;
  
  // 记录ID
  // Record ID
  String? recordId;
  
  @override
  void onInit() {
    super.onInit();
    // 从路由参数获取记录ID
    // Get record ID from route arguments
    final arguments = Get.arguments as Map<String, dynamic>?;
    recordId = arguments?['recordId'] as String?;
    
    if (recordId != null) {
      loadRecordDetail();
    }
  }
  
  @override
  void onClose() {
    contentController.dispose();
    super.onClose();
  }
  
  /// 加载记录详情
  /// Load record detail
  Future<void> loadRecordDetail() async {
    if (recordId == null) return;
    
    try {
      isLoading.value = true;
      clearError();
      
      // 并行加载记录和媒体文件
      // Load record and media files in parallel
      final results = await Future.wait<dynamic>([
        _emotionRepository.getRecordById(recordId!),
        _mediaRepository.getMediaFilesByRecordId(recordId!),
      ]);
      
      final loadedRecord = results[0] as EmotionRecord?;
      final loadedMediaFiles = results[1] as List<MediaFile>;
      
      if (loadedRecord != null) {
        record.value = loadedRecord;
        mediaFiles.assignAll(loadedMediaFiles);
        
        // 初始化编辑表单
        // Initialize edit form
        contentController.text = loadedRecord.diaryContent ?? '';
        selectedIntensity.value = loadedRecord.intensity;
      } else {
        setError('记录不存在');
      }
      
    } catch (e) {
      setError('加载记录失败: ${e.toString()}');
    } finally {
      isLoading.value = false;
    }
  }
  
  /// 切换编辑模式
  /// Toggle edit mode
  void toggleEdit() {
    isEditing.value = !isEditing.value;
    
    if (isEditing.value && record.value != null) {
      // 进入编辑模式时重置表单
      // Reset form when entering edit mode
      contentController.text = record.value!.diaryContent ?? '';
      selectedIntensity.value = record.value!.intensity;
    }
  }
  
  /// 保存更改
  /// Save changes
  Future<void> saveChanges() async {
    if (record.value == null) return;
    
    try {
      isLoading.value = true;
      clearError();
      
      // 创建更新后的记录
      // Create updated record
      final updatedRecord = record.value!.copyWith(
        diaryContent: contentController.text.trim(),
        emotionIntensity: selectedIntensity.value,
        updatedAt: DateTime.now(),
      );
      
      // 更新数据库
      // Update database
      await _emotionRepository.updateRecord(updatedRecord);
      
      // 更新本地状态
      // Update local state
      record.value = updatedRecord;
      
      // 退出编辑模式
      // Exit edit mode
      isEditing.value = false;
      
      // 显示成功消息
      // Show success message
      Get.snackbar(
        '保存成功',
        '记录已更新',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.green,
        colorText: Colors.white,
      );
      
    } catch (e) {
      setError('保存失败: ${e.toString()}');
    } finally {
      isLoading.value = false;
    }
  }
  
  /// 删除记录
  /// Delete record
  Future<void> deleteRecord() async {
    if (record.value == null) return;
    
    try {
      isLoading.value = true;
      clearError();
      
      // 删除关联的媒体文件
      // Delete associated media files
      await _mediaRepository.deleteMediaFilesByRecordId(record.value!.id);
      
      // 删除记录
      // Delete record
      await _emotionRepository.deleteRecord(record.value!.id);
      
      // 显示成功消息
      // Show success message
      Get.snackbar(
        '删除成功',
        '记录已删除',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.green,
        colorText: Colors.white,
      );
      
      // 返回上一页
      // Go back to previous page
      Get.back();
      
    } catch (e) {
      setError('删除失败: ${e.toString()}');
    } finally {
      isLoading.value = false;
    }
  }
  
  /// 设置情绪强度
  /// Set emotion intensity
  void setIntensity(int intensity) {
    selectedIntensity.value = intensity;
  }
  
  /// 获取情绪强度描述
  /// Get emotion intensity description
  String getIntensityDescription(int intensity) {
    switch (intensity) {
      case 1:
      case 2:
        return '很轻微';
      case 3:
      case 4:
        return '轻微';
      case 5:
      case 6:
        return '中等';
      case 7:
      case 8:
        return '强烈';
      case 9:
      case 10:
        return '非常强烈';
      default:
        return '中等';
    }
  }
  
  /// 获取记录统计信息
  /// Get record statistics
  Map<String, dynamic> getRecordStats() {
    if (record.value == null) return {};
    
    final rec = record.value!;
    return {
      '字数': rec.diaryContent?.length ?? 0,
      '媒体文件': mediaFiles.length,
      '创建时间': AppUtils.formatDateTime(rec.createdAt),
      '最后更新': AppUtils.formatDateTime(rec.updatedAt),
    };
  }
  
  /// 检查是否有未保存的更改
  /// Check if there are unsaved changes
  bool get hasUnsavedChanges {
    if (record.value == null || !isEditing.value) return false;
    
    return contentController.text.trim() != (record.value!.diaryContent ?? '') ||
           selectedIntensity.value != record.value!.intensity;
  }
  
  /// 设置错误信息
  /// Set error message
  void setError(String message) {
    errorMessage.value = message;
  }
  
  /// 清除错误信息
  /// Clear error message
  void clearError() {
    errorMessage.value = '';
  }
  
  /// 播放音频
  /// Play audio
  Future<void> playAudio(String audioPath) async {
    try {
      if (isPlaying.value && currentPlayingPath.value == audioPath) {
        // 如果正在播放同一个文件，则暂停
        // If playing the same file, pause it
        stopAudio();
        return;
      }
      
      // 停止当前播放
      // Stop current playback
      stopAudio();
      
      // 开始播放新文件
      // Start playing new file
      isPlaying.value = true;
      currentPlayingPath.value = audioPath;
      
      // TODO: 实现实际的音频播放逻辑
      // TODO: Implement actual audio playback logic
      
    } catch (e) {
      setError('播放音频失败: ${e.toString()}');
      stopAudio();
    }
  }
  
  /// 停止音频播放
  /// Stop audio playback
  void stopAudio() {
    isPlaying.value = false;
    currentPlayingPath.value = '';
    
    // TODO: 实现实际的音频停止逻辑
    // TODO: Implement actual audio stop logic
  }
}